package com.momo.seckilling.utils;

import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import redis.clients.jedis.Jedis;

import java.util.Collections;

/**
 * Created by li on 2019/3/17.
 */
public class RedisLockUtil {
    private static Jedis jedis = new Jedis("127.0.0.1", 6379);
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;

    public static String get(String str) {
        return String.valueOf(jedis.get(str));
    }
    public static void set(String key,String v) {
        jedis.set(key, v);
    }

    public static boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) {

        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);

        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;

    }

    public static boolean releaseDistributedLock(String lockKey, String requestId) {

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));

        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;

    }


    public static void main(String[] args) {
//        jedis.set("testkey","testvalue");
//        String value = jedis.get("testkey");
//        System.out.println(value);

        boolean resultlock = tryGetDistributedLock("test1", "request1", 50000);
        System.out.println(resultlock);

        boolean resultunlock = releaseDistributedLock("test1", "request2");
        System.out.println(resultunlock);
    }


}
